import { useRef, useEffect, useState } from 'react';
import { useMap } from '@uiw/react-baidu-map';


interface propsType {
    address: string
}

const MyMap = (props: propsType) => {
    const divElm: any = useRef();

    const { address } = props

    // 地图的放缩等级
    const [zoom, setZoom] = useState(15)
    const { setContainer, map, setCenter, setAutoLocalCity } = useMap({
        enableScrollWheelZoom: true, // 启用滚轮放大缩小，默认禁用
        center: address,
    });

    // 默认触发 用来初始化地图
    useEffect(() => {
        if (divElm.current && !map) {
            // 初始化地图  
            setContainer(divElm.current);
        }
    });

    // 监听中心定位以及放缩等级大小
    useEffect(() => {
        if (map) {
            // 启用滚轮放大缩小，默认禁用
            map.setZoom(zoom);

            setCenter(address)
        }
    }, [zoom, map, address]);

    return (
        <>
            <button onClick={() => setZoom(zoom - 1)}>-</button>
            <span>{zoom || 15}</span>
            <button onClick={() => setZoom(zoom + 1)}>+</button>
            <button onClick={() => setCenter('北京')}>北京</button>
            <button onClick={() => setCenter('上海')}>上海</button>
            <button onClick={() => setAutoLocalCity(true)}>IP定位</button>
            {/* 地图高度350  宽度100% */}
            <div ref={divElm} style={{ height: 350 }} />
        </>
    )
}

export default MyMap